package view;

import controller.BookClickListener;
import controller.JTextFieldHintListener;
import controller.SelfQueryViewListener;
import pojo.Book;
import pojo.User;

import javax.swing.*;
import java.awt.*;
import java.util.Iterator;
import java.util.List;

public class SelfQueryView extends JPanel {
    JPanel panel,panel1,panel2;
    JLabel label1;
    JTextField textField1;
    JButton button;
    private List<Book> bookList;
    private User user;
    private BookClickListener bookClickListener;
    private SelfQueryViewListener selfQueryViewListener;
    public SelfQueryView(List<Book> bookList, User user){
        selfQueryViewListener=new SelfQueryViewListener(this);
        bookClickListener =new BookClickListener(user.getUserId(),user.getUserName(),null);
        this.bookList=bookList;
        this.user=user;
        this.add(this.getPanel(bookList));
    }
    public void refresh(List<Book> bookList) {
        this.remove(panel);
        panel2 = this.getPanel(bookList);
        this.add(panel2);
        this.validate();
    }
    public JPanel getPanel(List<Book> bookList){
        //north

        panel=new JPanel();
        panel.setLayout(new BorderLayout());
        label1 = new JLabel("搜索");
        panel.add(label1,BorderLayout.NORTH);
        JPanel jPanel = new JPanel();

        //center
        textField1=new JTextField(15);
        //JTextField 默认文字提示功能
        textField1.addFocusListener(new JTextFieldHintListener(textField1, "书号/书名/作者"));
        button=new JButton("查询");
        button.addActionListener(selfQueryViewListener);
        jPanel.add(textField1);
        jPanel.add(button);
        panel1 = new JPanel();
        panel1.setLayout(new BorderLayout());
        panel1.add(jPanel,BorderLayout.NORTH);

        //south
        String[] titles={"书号","书名","作者"};
        Object data[][] = new Object[bookList.size()][3];
        Iterator<Book> iter = bookList.iterator();
        int i = 0;
        while (iter.hasNext()) {
            Book book= iter.next();
            data[i][0] = book.getBookId();
            data[i][1] = book.getBookName();
            data[i][2]=book.getWriter();
            i++;
        }
        JTable table = new JTable(data,titles);
        JScrollPane jScrollPane = new JScrollPane(table);
        table.addMouseListener(bookClickListener);
        bookClickListener.setTable(table);
        panel1.add(jScrollPane);
        panel.add(panel1);
        return panel;
    }
    public JTextField getTextField1() {
        return textField1;
    }
}
